<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">订单管理</h1>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="table-toolbar">
      <div class="table-toolbar-left">
        <el-input
            v-model="searchForm.keyword"
            clearable
            placeholder="搜索订单号或用户名"
            style="width: 200px"
            @clear="handleSearch"
            @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon>
              <Search/>
            </el-icon>
          </template>
        </el-input>

        <el-select
            v-model="searchForm.status"
            clearable
            placeholder="订单状态"
            style="width: 120px"
            @change="handleSearch"
        >
          <el-option :value="1" label="待支付"/>
          <el-option :value="2" label="待发货"/>
          <el-option :value="3" label="待收货"/>
          <el-option :value="4" label="已完成"/>
          <el-option :value="0" label="已取消"/>
          <el-option :value="5" label="已过期"/>
        </el-select>

        <el-select
            v-model="searchForm.paymentStatus"
            clearable
            placeholder="支付状态"
            style="width: 120px"
            @change="handleSearch"
        >
          <el-option :value="0" label="未支付"/>
          <el-option :value="1" label="已支付"/>
        </el-select>

        <el-date-picker
            v-model="searchForm.dateRange"
            end-placeholder="结束日期"
            range-separator="至"
            start-placeholder="开始日期"
            style="width: 240px"
            type="daterange"
            @change="handleSearch"
        />

        <el-button type="primary" @click="handleSearch">
          <el-icon>
            <Search/>
          </el-icon>
          搜索
        </el-button>

        <el-button @click="handleReset">
          <el-icon>
            <Refresh/>
          </el-icon>
          重置
        </el-button>
      </div>

      <div class="table-toolbar-right">
        <el-button @click="handleRefresh">
          <el-icon>
            <Refresh/>
          </el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 订单表格 -->
    <div class="table-container">
      <el-table
          v-loading="loading"
          :data="orders"
          stripe
          style="width: 100%"
      >
        <el-table-column label="订单ID" prop="id" width="100"/>

        <el-table-column label="订单号" prop="orderNo" width="180"/>

        <el-table-column label="用户" prop="username" width="120"/>

        <el-table-column label="订单金额" width="120">
          <template #default="{ row }">
            <span class="order-amount">¥{{ row.totalAmount }}</span>
          </template>
        </el-table-column>

        <el-table-column label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusInfo(row.status).type" size="small">
              {{ getOrderStatusInfo(row.status).text }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="支付方式" width="100">
          <template #default="{ row }">
            {{ getPaymentTypeName(row.paymentType) }}
          </template>
        </el-table-column>

        <el-table-column label="支付状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getPaymentStatusInfo(row.paymentStatus).type" size="small">
              {{ getPaymentStatusInfo(row.paymentStatus).text }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="发货状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getDeliveryStatusInfo(row.deliveryStatus).type" size="small">
              {{ getDeliveryStatusInfo(row.deliveryStatus).text }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="收货人" prop="receiverName" width="100"/>

        <el-table-column label="收货电话" prop="receiverPhone" width="130"/>

        <el-table-column label="下单时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="200">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                  size="small"
                  type="primary"
                  @click="handleViewDetail(row)"
              >
                详情
              </el-button>

              <el-button
                  v-if="row.status === 2 && row.paymentStatus === 1"
                  size="small"
                  type="success"
                  @click="handleDeliver(row)"
              >
                发货
              </el-button>

              <el-button
                  v-if="row.status === 1"
                  size="small"
                  type="warning"
                  @click="handleCancel(row)"
              >
                取消
              </el-button>
              <el-button
                  size="small"
                  type="info"
                  @click="handleRemark(row)"
              >
                备注
              </el-button>


            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 发货对话框 -->
    <DeliveryDialog
        v-model="deliveryDialogVisible"
        :order="selectedOrder"
        @success="handleDeliverySuccess"
    />

    <!-- 备注对话框 -->
    <RemarkDialog
        v-model="remarkDialogVisible"
        :order="selectedOrder"
        @success="handleRemarkSuccess"
    />
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Refresh, Search} from '@element-plus/icons-vue'
import {useOrderStore} from '@/store/order'
import {formatDateTime} from '@/utils'
import DeliveryDialog from './DeliveryDialog.vue'
import RemarkDialog from './RemarkDialog.vue'

// 路由
const router = useRouter()

// Store
const orderStore = useOrderStore()

// 响应式数据
const searchForm = reactive({
  keyword: '',
  status: null,
  paymentStatus: null,
  dateRange: null
})

const deliveryDialogVisible = ref(false)
const remarkDialogVisible = ref(false)
const selectedOrder = ref(null)

// 计算属性
const orders = computed(() => orderStore.orders)
const loading = computed(() => orderStore.loading)
const total = computed(() => orderStore.total)
const currentPage = computed({
  get: () => orderStore.currentPage,
  set: (value) => orderStore.setPagination(value, orderStore.pageSize)
})
const pageSize = computed({
  get: () => orderStore.pageSize,
  set: (value) => orderStore.setPagination(orderStore.currentPage, value)
})

// 方法
const handleSearch = () => {
  orderStore.setPagination(1, pageSize.value)
  loadOrderList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: null,
    paymentStatus: null,
    dateRange: null
  })
  handleSearch()
}

const handleRefresh = () => {
  loadOrderList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  loadOrderList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadOrderList()
}

const handleViewDetail = (order) => {
  router.push(`/orders/${order.id}`)
}

const handleDeliver = (order) => {
  selectedOrder.value = order
  deliveryDialogVisible.value = true
}

const handleCancel = async (order) => {
  try {
    await ElMessageBox.confirm(
        `确定要取消订单 "${order.orderNo}" 吗？`,
        '确认取消',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await orderStore.cancelOrder(order.id, {reason: '管理员取消'})
    ElMessage.success('订单取消成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消失败，请重试')
    }
  }
}


const handleDeliverySuccess = () => {
  deliveryDialogVisible.value = false
  loadOrderList()
}

const handleRemark = (order) => {
  selectedOrder.value = order
  remarkDialogVisible.value = true
}

const handleRemarkSuccess = () => {
  remarkDialogVisible.value = false
  loadOrderList()
}

const getPaymentTypeName = (paymentType) => {
  const typeMap = {
    1: '微信支付',
    2: '支付宝支付'
  }
  return typeMap[paymentType] || '未知'
}

// const handleRemarkSuccess = () => {
//   remarkDialogVisible.value = false
//   loadOrderList()
// }

const getOrderStatusInfo = (status) => {
  return orderStore.getOrderStatusInfo(status)
}

const getPaymentStatusInfo = (status) => {
  return orderStore.getPaymentStatusInfo(status)
}

const getDeliveryStatusInfo = (status) => {
  return orderStore.getDeliveryStatusInfo(status)
}

const loadOrderList = async () => {
  try {
    const params = {...searchForm}

    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    delete params.dateRange

    await orderStore.getOrderList(params)
  } catch (error) {
    console.error('加载订单列表失败:', error)
    ElMessage.error('加载失败，请重试')
  }
}

// 生命周期
onMounted(() => {
  loadOrderList()
})
</script>

<style scoped>
.order-amount {
  color: #e6a23c;
  font-weight: 600;
}

.page-container {
  padding: var(--admin-space-lg);
  background: var(--admin-bg-layout);
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: var(--admin-space-lg);
  padding: var(--admin-space-lg);
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  box-shadow: var(--admin-shadow-sm);
  border: 1px solid var(--admin-border-light);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0;
  color: var(--admin-text-primary);
  font-size: var(--admin-font-xl);
  font-weight: var(--admin-font-semibold);
  line-height: var(--admin-line-height-sm);
}

.table-container {
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  box-shadow: var(--admin-shadow-sm);
  border: 1px solid var(--admin-border-light);
  overflow: hidden;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
  padding: var(--admin-space-lg);
  background: var(--admin-bg-secondary);
  border-bottom: 1px solid var(--admin-border-light);
}

.table-toolbar-left {
  display: flex;
  gap: var(--admin-space-sm);
  align-items: center;
  flex-wrap: wrap;
}

.table-toolbar-right {
  display: flex;
  gap: var(--admin-space-sm);
  align-items: center;
  flex-wrap: wrap;
}

.pagination-container {
  padding: var(--admin-space-lg);
  text-align: center;
  background: var(--admin-bg-secondary);
  border-top: 1px solid var(--admin-border-light);
}

/* 订单状态样式 */
.order-status {
  font-size: var(--admin-font-xs);
  padding: var(--admin-space-xs) var(--admin-space-sm);
  border-radius: var(--admin-radius-sm);
  font-weight: var(--admin-font-medium);
  display: inline-flex;
  align-items: center;
  line-height: 1;
}

.status-pending {
  background: var(--admin-warning-bg);
  color: var(--admin-warning);
  border: 1px solid var(--admin-warning-light);
}

.status-paid {
  background: var(--admin-info-bg);
  color: var(--admin-info);
  border: 1px solid var(--admin-primary-light);
}

.status-shipped {
  background: var(--admin-primary-bg);
  color: var(--admin-primary);
  border: 1px solid var(--admin-primary-light);
}

.status-completed {
  background: var(--admin-success-bg);
  color: var(--admin-success);
  border: 1px solid var(--admin-success-light);
}

.status-cancelled {
  background: var(--admin-error-bg);
  color: var(--admin-error);
  border: 1px solid var(--admin-error-light);
}

/* 价格显示样式 */
.order-amount {
  font-weight: var(--admin-font-semibold);
  color: var(--admin-error);
  font-size: var(--admin-font-sm);
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: var(--admin-space-xs);
  align-items: center;
}

.action-buttons .el-button {
  padding: var(--admin-space-xs) var(--admin-space-sm);
  font-size: var(--admin-font-xs);
  height: var(--admin-height-sm);
  border-radius: var(--admin-radius-sm);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: var(--admin-space-md);
    align-items: flex-start;
  }

  .table-toolbar {
    flex-direction: column;
    gap: var(--admin-space-sm);
    align-items: stretch;
  }

  .table-toolbar-left,
  .table-toolbar-right {
    justify-content: center;
  }

  .action-buttons {
    flex-direction: column;
    width: 100%;
  }

  .action-buttons .el-button {
    width: 100%;
    justify-content: center;
  }
}
</style>
